<template>
  <div class="bom-template-container">
    <!-- 顶部工具栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="handleAddTemplate">
        <el-icon>
          <Plus />
        </el-icon>新建模板
      </el-button>
      <el-button type="success" @click="handleImport">
        <el-icon>
          <Upload />
        </el-icon>导入
      </el-button>
      <el-button type="danger" @click="handleExport">
        <el-icon>
          <Download />
        </el-icon>导出
      </el-button>
      <el-button type="text" @click="handleRefresh">
        <el-icon>
          <Refresh />
        </el-icon>刷新
      </el-button>
    </div>

    <!-- 筛选查询区域 -->
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="组合件">
        <el-select v-model="searchForm.assembly" placeholder="请选择组合件">
          <el-option v-for="item in assemblyOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="子件">
        <el-select v-model="searchForm.subAssembly" placeholder="请选择子件">
          <el-option v-for="item in subAssemblyOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="模板类型">
        <el-select v-model="searchForm.templateType" placeholder="请选择模板类型">
          <el-option label="拆卸模板" value="拆卸模板"></el-option>
          <el-option label="组装模板" value="组装模板"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">
          <el-icon>
            <Search />
          </el-icon>查询
        </el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 主体内容区域 -->
    <div class="content-area">
      <!-- 左侧模板分类 -->
      <div class="left-panel">
        <div class="category-header">
          <el-input v-model="categorySearch" placeholder="搜索分类" clearable @clear="handleCategorySearchClear">
            <template #prefix>
              <el-icon>
                <Search />
              </el-icon>
            </template>
          </el-input>
          <el-button type="text" size="small" @click="handleAddCategory">
            <el-icon>
              <Plus />
            </el-icon>新建分类
          </el-button>
        </div>
        <el-tree :data="categoryTree" :props="treeProps" :filter-node-method="filterCategory" v-model="selectedCategory"
          @node-click="handleCategoryClick" @node-expand="handleCategoryExpand" class="category-tree" show-checkbox
          node-key="id" highlight-current />
      </div>

      <!-- 右侧内容区域 -->
      <div class="right-panel">
        <!-- 组装件列表 -->
        <el-card class="assembly-card">
          <div class="card-header">
            <h3>组装件列表</h3>
            <div class="card-actions">
              <el-button type="primary" size="small" @click="handleAddAssembly">
                <el-icon>
                  <Plus />
                </el-icon>新增
              </el-button>
              <el-button type="danger" size="small" @click="handleDeleteAssembly"
                :disabled="!selectedAssemblyIds.length">
                <el-icon>
                  <Delete />
                </el-icon>删除
              </el-button>
              <el-button type="warning" size="small" @click="handleEditAssembly"
                :disabled="selectedAssemblyIds.length !== 1">
                <el-icon>
                  <Edit />
                </el-icon>编辑
              </el-button>
            </div>
          </div>

          <el-table :data="filteredAssemblyList" border stripe size="small" @row-click="handleRowClick"
            @selection-change="handleSelectionChange" ref="assemblyTableRef">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="id" label="ID" width="80"></el-table-column>
            <el-table-column prop="seq" label="序号" width="80"></el-table-column>
            <el-table-column prop="templateCode" label="模板编号"></el-table-column>
            <el-table-column prop="templateName" label="模板名称"></el-table-column>
            <el-table-column prop="templateType" label="模板类型"></el-table-column>
            <el-table-column prop="combination" label="组合件"></el-table-column>
            <el-table-column prop="product" label="商品"></el-table-column>
            <el-table-column prop="combinationQty" label="组合件数量" width="120"></el-table-column>
            <el-table-column prop="creator" label="制作人"></el-table-column>
            <el-table-column prop="createTime" label="创建时间"></el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button type="text" size="small" @click="handleEditAssembly(scope.row)">
                  <el-icon>
                    <Edit />
                  </el-icon>
                </el-button>
                <el-button type="text" size="small" @click="handleDeleteAssembly([scope.row.id])">
                  <el-icon>
                    <Delete />
                  </el-icon>
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="assemblyTotal"
            :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" v-model:current-page="currentPage"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" class="pagination" />
        </el-card>

        <!-- 子件列表（关联当前选中组装件） -->
        <el-card class="subassembly-card" v-if="currentAssembly">
          <div class="card-header">
            <h3>子件列表 - {{ currentAssembly.combination }}</h3>
            <div class="card-actions">
              <el-button type="primary" size="small" @click="handleAddSubAssembly">
                <el-icon>
                  <Plus />
                </el-icon>新增子件
              </el-button>
              <el-button type="danger" size="small" @click="handleDeleteSubAssembly"
                :disabled="!selectedSubAssemblyIds.length">
                <el-icon>
                  <Delete />
                </el-icon>删除
              </el-button>
              <el-button type="warning" size="small" @click="handleEditSubAssembly"
                :disabled="selectedSubAssemblyIds.length !== 1">
                <el-icon>
                  <Edit />
                </el-icon>编辑
              </el-button>
            </div>
          </div>

          <el-table :data="subAssemblyList" border stripe size="small"
            @selection-change="handleSubAssemblySelectionChange" ref="subAssemblyTableRef">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="seq" label="序号" width="80"></el-table-column>
            <el-table-column prop="subName" label="子件名称"></el-table-column>
            <el-table-column prop="product" label="商品"></el-table-column>
            <el-table-column prop="productCode" label="商品编码"></el-table-column>
            <el-table-column prop="qty" label="数量" width="80"></el-table-column>
            <el-table-column prop="unit" label="单位"></el-table-column>
            <el-table-column prop="warehouse" label="仓库"></el-table-column>
            <el-table-column prop="remark" label="备注"></el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button type="text" size="small" @click="handleEditSubAssembly(scope.row)">
                  <el-icon>
                    <Edit />
                  </el-icon>
                </el-button>
                <el-button type="text" size="small" @click="handleDeleteSubAssembly([scope.row.id])">
                  <el-icon>
                    <Delete />
                  </el-icon>
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 子件表格为空时的提示 -->
          <div v-if="!subAssemblyList.length" class="empty-table">
            <el-empty description="暂无子件数据" :image-size="100">
              <template #bottom>
                <el-button type="primary" @click="handleAddSubAssembly">添加子件</el-button>
              </template>
            </el-empty>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 新建/编辑模板对话框 -->
    <el-dialog :visible="templateDialogVisible" @close="templateDialogVisible = false" title="模板信息">
      <el-form :model="templateForm" ref="templateFormRef" label-width="120px">
        <el-form-item label="模板编号" prop="templateCode">
          <el-input v-model="templateForm.templateCode" />
        </el-form-item>
        <el-form-item label="模板名称" prop="templateName">
          <el-input v-model="templateForm.templateName" />
        </el-form-item>
        <el-form-item label="模板类型" prop="templateType">
          <el-select v-model="templateForm.templateType" placeholder="请选择模板类型">
            <el-option label="拆卸模板" value="拆卸模板"></el-option>
            <el-option label="组装模板" value="组装模板"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="组合件" prop="combination">
          <el-input v-model="templateForm.combination" />
        </el-form-item>
        <el-form-item label="商品" prop="product">
          <el-input v-model="templateForm.product" />
        </el-form-item>
        <el-form-item label="组合件数量" prop="combinationQty">
          <el-input-number v-model="templateForm.combinationQty" min="0" step="0.01" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="templateForm.remark" rows="4" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="templateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveTemplate">保存</el-button>
      </template>
    </el-dialog>

    <!-- 新建/编辑子件对话框 -->
    <el-dialog :visible="subAssemblyDialogVisible" @close="subAssemblyDialogVisible = false" title="子件信息">
      <el-form :model="subAssemblyForm" ref="subAssemblyFormRef" label-width="120px">
        <el-form-item label="子件名称" prop="subName">
          <el-input v-model="subAssemblyForm.subName" />
        </el-form-item>
        <el-form-item label="商品" prop="product">
          <el-input v-model="subAssemblyForm.product" />
        </el-form-item>
        <el-form-item label="商品编码" prop="productCode">
          <el-input v-model="subAssemblyForm.productCode" />
        </el-form-item>
        <el-form-item label="数量" prop="qty">
          <el-input-number v-model="subAssemblyForm.qty" min="0" step="0.01" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="subAssemblyForm.unit" />
        </el-form-item>
        <el-form-item label="仓库" prop="warehouse">
          <el-input v-model="subAssemblyForm.warehouse" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="subAssemblyForm.remark" rows="4" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="subAssemblyDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveSubAssembly">保存</el-button>
      </template>
    </el-dialog>

    <!-- 新建分类对话框 -->
    <el-dialog :visible="categoryDialogVisible" @close="categoryDialogVisible = false" title="新建分类">
      <el-form :model="categoryForm" ref="categoryFormRef" label-width="120px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" />
        </el-form-item>
        <el-form-item label="父级分类" prop="parentId">
          <el-select v-model="categoryForm.parentId" placeholder="请选择父级分类">
            <el-option label="全部" value="0"></el-option>
            <el-option v-for="item in flatCategoryList" :key="item.id" :label="item.label" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="categoryDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveCategory">保存</el-button>
      </template>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :visible="importDialogVisible" @close="importDialogVisible = false" title="导入数据">
      <el-form :model="importForm" ref="importFormRef" label-width="120px">
        <el-form-item label="选择文件">
          <el-upload class="upload-demo" ref="uploadRef" :action="uploadUrl" :on-success="handleUploadSuccess"
            :on-error="handleUploadError" :before-upload="beforeUpload" accept=".xlsx,.xls">
            <el-button size="small" type="primary">点击上传</el-button>
            <div class="el-upload__tip">
              只能上传 xlsx/xls 文件，且不超过 10MB
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="importDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitImport">确认导入</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue';
import {
  ElButton, ElTable, ElTableColumn, ElForm, ElFormItem, ElInput,
  ElSelect, ElOption, ElDialog, ElPagination, ElIcon, ElTree,
  ElCard, ElInputNumber, ElEmpty, ElUpload, ElMessage, ElMessageBox
} from 'element-plus';
import {
  Plus, Delete, Edit, Search, Refresh, Upload, Download
} from '@element-plus/icons-vue';

// 模拟数据
const assemblyOptions = [
  { label: '黑巧克力礼盒', value: '黑巧克力礼盒' },
  { label: '白巧克力礼盒', value: '白巧克力礼盒' },
  { label: '冰清紫云', value: '冰清紫云' },
  { label: '林木青云', value: '林木青云' },
];

const subAssemblyOptions = [
  { label: '巧克力块', value: '巧克力块' },
  { label: '白巧克力块', value: '白巧克力块' },
  { label: '包装盒', value: '包装盒' },
  { label: '高档礼盒', value: '高档礼盒' },
  { label: '青云原料1', value: '青云原料1' },
  { label: '青云原料2', value: '青云原料2' },
];

// 模板分类树
const categoryTree = ref([
  {
    id: 1,
    label: '全部',
    children: [
      { id: 2, label: '未分类' },
      {
        id: 3,
        label: '食品类',
        children: [
          { id: 4, label: '巧克力系列' },
          { id: 5, label: '饼干系列' }
        ]
      },
      {
        id: 6,
        label: '礼盒类',
        children: [
          { id: 7, label: '节日礼盒' },
          { id: 8, label: '普通礼盒' }
        ]
      },
    ],
  },
]);

// 扁平化分类列表（用于下拉选择）
const flatCategoryList = ref([]);

// 组装件列表
const assemblyList = ref([
  {
    id: 1,
    seq: 1,
    templateCode: 'TEMP-20230518-001',
    templateName: '巧克力礼盒',
    templateType: '拆卸模板',
    combination: '黑巧克力礼盒',
    product: 'SP0071 巧克力礼盒 20g*20块',
    combinationQty: 1,
    creator: '体验用户1',
    createTime: '2023-05-18',
    remark: '',
    categoryId: 4, // 巧克力系列
  },
  {
    id: 2,
    seq: 2,
    templateCode: 'TEMP-20230517-002',
    templateName: '巧克力礼盒',
    templateType: '组装模板',
    combination: '白巧克力礼盒',
    product: 'SP0006 白巧克力礼盒 40g*20块',
    combinationQty: 1,
    creator: '体验用户1',
    createTime: '2023-05-17',
    remark: '来源于创建平台K/3 D0023051...',
    categoryId: 4, // 巧克力系列
  },
  {
    id: 3,
    seq: 3,
    templateCode: 'TEMP-20221212-003',
    templateName: '林木青云礼盒',
    templateType: '组装模板',
    combination: '林木青云',
    product: 'H03.02.01.001 林木青云 150G',
    combinationQty: 1.36,
    creator: '体验用户1',
    createTime: '2022-12-12',
    remark: '',
    categoryId: 7, // 节日礼盒
  },
  {
    id: 4,
    seq: 4,
    templateCode: 'TEMP-20230105-004',
    templateName: '冰清紫云礼盒',
    templateType: '组装模板',
    combination: '冰清紫云',
    product: 'H03.02.01.002 冰清紫云 120G',
    combinationQty: 1.2,
    creator: '体验用户1',
    createTime: '2023-01-05',
    remark: '',
    categoryId: 7, // 节日礼盒
  },
  {
    id: 5,
    seq: 5,
    templateCode: 'TEMP-20230315-005',
    templateName: '饼干礼盒',
    templateType: '拆卸模板',
    combination: '草莓饼干礼盒',
    product: 'SP0015 草莓饼干礼盒 100g*10盒',
    combinationQty: 1,
    creator: '体验用户1',
    createTime: '2023-03-15',
    remark: '',
    categoryId: 5, // 饼干系列
  },
]);

// 模拟子件关联数据
const mockSubAssemblyMap = {
  1: [
    { id: 101, seq: 1, subName: '巧克力块', product: 'SP0071-1', productCode: 'SP0071-1', qty: 20, unit: '块', warehouse: '仓库A', remark: '' },
    { id: 102, seq: 2, subName: '礼盒包装', product: 'BOX-001', productCode: 'BOX-001', qty: 1, unit: '个', warehouse: '仓库B', remark: '' },
  ],
  2: [
    { id: 201, seq: 1, subName: '白巧克力块', product: 'SP0006-1', productCode: 'SP0006-1', qty: 20, unit: '块', warehouse: '仓库A', remark: '' },
    { id: 202, seq: 2, subName: '高档礼盒', product: 'BOX-002', productCode: 'BOX-002', qty: 1, unit: '个', warehouse: '仓库C', remark: '' },
  ],
  3: [
    { id: 301, seq: 1, subName: '青云原料1', product: 'H03-01', productCode: 'H03-01', qty: 100, unit: 'G', warehouse: '仓库D', remark: '' },
    { id: 302, seq: 2, subName: '青云原料2', product: 'H03-02', productCode: 'H03-02', qty: 50, unit: 'G', warehouse: '仓库D', remark: '' },
    { id: 303, seq: 3, subName: '精美包装', product: 'WRAP-003', productCode: 'WRAP-003', qty: 1, unit: '个', warehouse: '仓库E', remark: '' },
  ],
  4: [
    { id: 401, seq: 1, subName: '紫云原料', product: 'H03-03', productCode: 'H03-03', qty: 80, unit: 'G', warehouse: '仓库D', remark: '' },
    { id: 402, seq: 2, subName: '冰清原料', product: 'H03-04', productCode: 'H03-04', qty: 40, unit: 'G', warehouse: '仓库D', remark: '' },
    { id: 403, seq: 3, subName: '特制包装', product: 'WRAP-004', productCode: 'WRAP-004', qty: 1, unit: '个', warehouse: '仓库E', remark: '' },
  ],
  5: [
    { id: 501, seq: 1, subName: '草莓饼干', product: 'SP0015-1', productCode: 'SP0015-1', qty: 10, unit: '盒', warehouse: '仓库F', remark: '' },
    { id: 502, seq: 2, subName: '饼干礼盒', product: 'BOX-005', productCode: 'BOX-005', qty: 1, unit: '个', warehouse: '仓库G', remark: '' },
  ],
};

// 响应式数据
const searchForm = ref({
  assembly: '',
  subAssembly: '',
  templateType: '',
});

const subAssemblyList = ref([]);
const currentAssembly = ref(null);
const categorySearch = ref('');
const selectedCategory = ref(1); // 默认选中"全部"
const treeProps = { children: 'children', label: 'label' };
const pageSize = ref(10);
const currentPage = ref(1);
const assemblyTotal = ref(assemblyList.value.length);
const selectedAssemblyIds = ref([]);
const selectedSubAssemblyIds = ref([]);

// 对话框相关
const templateDialogVisible = ref(false);
const templateForm = ref({
  id: null,
  templateCode: '',
  templateName: '',
  templateType: '组装模板',
  combination: '',
  product: '',
  combinationQty: 1,
  remark: '',
});
const templateFormRef = ref(null);

const subAssemblyDialogVisible = ref(false);
const subAssemblyForm = ref({
  id: null,
  seq: null,
  subName: '',
  product: '',
  productCode: '',
  qty: 1,
  unit: '',
  warehouse: '',
  remark: '',
});
const subAssemblyFormRef = ref(null);

const categoryDialogVisible = ref(false);
const categoryForm = ref({
  id: null,
  name: '',
  parentId: 0,
});
const categoryFormRef = ref(null);

const importDialogVisible = ref(false);
const importForm = ref({});
const importFormRef = ref(null);
const uploadRef = ref(null);
const uploadUrl = ref('https://example.com/upload'); // 模拟上传URL

// 表格引用
const assemblyTableRef = ref(null);
const subAssemblyTableRef = ref(null);

// 工具方法：扁平化树结构
const flattenTree = (tree, parentId = 0, level = 0) => {
  let result = [];
  tree.forEach(item => {
    const node = { ...item, parentId, level };
    result.push(node);
    if (item.children && item.children.length > 0) {
      result = result.concat(flattenTree(item.children, item.id, level + 1));
    }
  });
  return result;
};

// 计算属性：获取当前分类下的组装件
const filteredAssemblyList = computed(() => {
  if (selectedCategory.value === 1) { // 全部
    return assemblyList.value.slice(
      (currentPage.value - 1) * pageSize.value,
      currentPage.value * pageSize.value
    );
  }

  const filtered = assemblyList.value.filter(item => item.categoryId === selectedCategory.value);
  return filtered.slice(
    (currentPage.value - 1) * pageSize.value,
    currentPage.value * pageSize.value
  );
});

// 计算总数量
watch([selectedCategory, assemblyList], () => {
  if (selectedCategory.value === 1) {
    assemblyTotal.value = assemblyList.value.length;
  } else {
    assemblyTotal.value = assemblyList.value.filter(item => item.categoryId === selectedCategory.value).length;
  }
});

// 方法
const handleSearch = () => {
  console.log('查询条件：', searchForm.value);
  // 实际可调用接口，根据 searchForm 筛选组装件列表
  currentPage.value = 1;
};

const resetSearch = () => {
  searchForm.value = {
    assembly: '',
    subAssembly: '',
    templateType: '',
  };
  currentPage.value = 1;
};

const handleRowClick = (row) => {
  // 点击组装件行，加载关联子件
  currentAssembly.value = row;
  subAssemblyList.value = mockSubAssemblyMap[row.id] || [];

  // 清空子件选择
  if (subAssemblyTableRef.value) {
    subAssemblyTableRef.value.clearSelection();
  }
  selectedSubAssemblyIds.value = [];
};

const handleCategoryClick = (node) => {
  console.log('选中分类：', node);
  selectedCategory.value = node.id;
  currentPage.value = 1;

  // 清空组装件选择
  if (assemblyTableRef.value) {
    assemblyTableRef.value.clearSelection();
  }
  selectedAssemblyIds.value = [];
  currentAssembly.value = null;
  subAssemblyList.value = [];
};

const handleCategoryExpand = (node) => {
  console.log('展开分类：', node);
};

const filterCategory = (value, node) => {
  if (!value) return true;
  return node.label.includes(value);
};

const handleCategorySearchClear = () => {
  categorySearch.value = '';
};

const handleSelectionChange = (val) => {
  selectedAssemblyIds.value = val.map(item => item.id);
};

const handleSubAssemblySelectionChange = (val) => {
  selectedSubAssemblyIds.value = val.map(item => item.id);
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
};

// 模板操作
const handleAddTemplate = () => {
  templateForm.value = {
    id: null,
    templateCode: generateTemplateCode(),
    templateName: '',
    templateType: '组装模板',
    combination: '',
    product: '',
    combinationQty: 1,
    remark: '',
  };
  templateDialogVisible.value = true;
};

// 生成模板编号
const generateTemplateCode = () => {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const seq = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
  return `TEMP-${year}${month}${day}-${seq}`;
};

const handleEditAssembly = (row) => {
  if (!row && selectedAssemblyIds.value.length !== 1) {
    ElMessage.warning('请选择一个组装件进行编辑');
    return;
  }

  const targetRow = row || assemblyList.value.find(item => item.id === selectedAssemblyIds.value[0]);
  if (!targetRow) return;

  templateForm.value = { ...targetRow };
  templateDialogVisible.value = true;
};

const handleDeleteAssembly = (ids = []) => {
  const deleteIds = ids.length > 0 ? ids : selectedAssemblyIds.value;
  if (deleteIds.length === 0) {
    ElMessage.warning('请选择要删除的组装件');
    return;
  }

  ElMessageBox.confirm(
    `确定要删除选中的 ${deleteIds.length} 个组装件吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // 模拟删除操作
    for (const id of deleteIds) {
      const index = assemblyList.value.findIndex(item => item.id === id);
      if (index !== -1) {
        assemblyList.value.splice(index, 1);

        // 如果删除的是当前选中的组装件
        if (currentAssembly.value && currentAssembly.value.id === id) {
          currentAssembly.value = null;
          subAssemblyList.value = [];
        }
      }
    }

    // 更新总数
    if (selectedCategory.value === 1) {
      assemblyTotal.value = assemblyList.value.length;
    } else {
      assemblyTotal.value = assemblyList.value.filter(item => item.categoryId === selectedCategory.value).length;
    }

    // 清空选择
    if (assemblyTableRef.value) {
      assemblyTableRef.value.clearSelection();
    }
    selectedAssemblyIds.value = [];

    ElMessage.success('删除成功');
  }).catch(() => {
    // 取消操作
  });
};

const handleSaveTemplate = () => {
  if (!templateFormRef.value) return;

  templateFormRef.value.validate((valid) => {
    if (valid) {
      if (templateForm.value.id) {
        // 更新操作
        const index = assemblyList.value.findIndex(item => item.id === templateForm.value.id);
        if (index !== -1) {
          assemblyList.value[index] = { ...templateForm.value };

          // 如果更新的是当前选中的组装件
          if (currentAssembly.value && currentAssembly.value.id === templateForm.value.id) {
            currentAssembly.value = { ...templateForm.value };
          }
        }
      } else {
        // 新增操作
        const newId = Math.max(0, ...assemblyList.value.map(item => item.id)) + 1;
        const newAssembly = {
          ...templateForm.value,
          id: newId,
          seq: assemblyList.value.length + 1,
          creator: '体验用户1',
          createTime: new Date().toISOString().split('T')[0],
          categoryId: selectedCategory.value || 2, // 默认放到"未分类"
        };

        assemblyList.value.push(newAssembly);
        
        // 更新总数
        if (selectedCategory.value === 1 || newAssembly.categoryId === selectedCategory.value) {
          assemblyTotal.value = assemblyList.value.length;
        } else {
          assemblyTotal.value = assemblyList.value.filter(item => item.categoryId === selectedCategory.value).length;
        }
      }

      templateDialogVisible.value = false;
      ElMessage.success('保存成功');
    } else {
      ElMessage.error('表单验证失败，请检查');
      return false;
    }
  });
};

// 子件操作
const handleAddSubAssembly = () => {
  if (!currentAssembly.value) {
    ElMessage.warning('请先选择一个组装件');
    return;
  }

  subAssemblyForm.value = {
    id: null,
    seq: (subAssemblyList.value.length > 0 ? Math.max(...subAssemblyList.value.map(item => item.seq)) : 0) + 1,
    subName: '',
    product: '',
    productCode: '',
    qty: 1,
    unit: '',
    warehouse: '',
    remark: '',
  };    subAssemblyDialogVisible.value = true;
};

const handleEditSubAssembly = (row) => {
  if (!row && selectedSubAssemblyIds.value.length !== 1) {
    ElMessage.warning('请选择一个子件进行编辑');
    return;
  }

  const targetRow = row || subAssemblyList.value.find(item => item.id === selectedSubAssemblyIds.value[0]);
  if (!targetRow) return;

  subAssemblyForm.value = { ...targetRow };
  subAssemblyDialogVisible.value = true;
};

const handleDeleteSubAssembly = (ids = []) => {
  const deleteIds = ids.length > 0 ? ids : selectedSubAssemblyIds.value;
  if (deleteIds.length === 0) {
    ElMessage.warning('请选择要删除的子件');
    return;
  }

  ElMessageBox.confirm(
    `确定要删除选中的 ${deleteIds.length} 个子件吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // 模拟删除操作
    for (const id of deleteIds) {
      const index = subAssemblyList.value.findIndex(item => item.id === id);
      if (index !== -1) {
        subAssemblyList.value.splice(index, 1);
      }
    }

    // 更新序号
    subAssemblyList.value.forEach((item, index) => {
      item.seq = index + 1;
    });

    // 清空选择
    if (subAssemblyTableRef.value) {
      subAssemblyTableRef.value.clearSelection();
    }
    selectedSubAssemblyIds.value = [];

    ElMessage.success('删除成功');
  }).catch(() => {
    // 取消操作
  });
};

const handleSaveSubAssembly = () => {
  if (!subAssemblyFormRef.value) return;

  subAssemblyFormRef.value.validate((valid) => {
    if (valid) {
      if (subAssemblyForm.value.id) {
        // 更新操作
        const index = subAssemblyList.value.findIndex(item => item.id === subAssemblyForm.value.id);
        if (index !== -1) {
          subAssemblyList.value[index] = { ...subAssemblyForm.value };
        }
      } else {
        // 新增操作
        const newId = currentAssembly.value.id * 100 + (subAssemblyList.value.length + 1);
        const newSubAssembly = {
          ...subAssemblyForm.value,
          id: newId,
        };

        subAssemblyList.value.push(newSubAssembly);
        
        // 更新模拟数据
        if (!mockSubAssemblyMap[currentAssembly.value.id]) {
          mockSubAssemblyMap[currentAssembly.value.id] = [];
        }
        mockSubAssemblyMap[currentAssembly.value.id].push(newSubAssembly);
      }

      // 更新序号
      subAssemblyList.value.sort((a, b) => a.seq - b.seq);
      subAssemblyList.value.forEach((item, index) => {
        item.seq = index + 1;
      });

      subAssemblyDialogVisible.value = false;
      ElMessage.success('保存成功');
    } else {
      ElMessage.error('表单验证失败，请检查');
      return false;
    }
  });
};

// 分类操作
const handleAddCategory = () => {
  categoryForm.value = {
    id: null,
    name: '',
    parentId: selectedCategory.value || 0,
  };
  categoryDialogVisible.value = true;
};

const handleSaveCategory = () => {
  if (!categoryFormRef.value) return;

  categoryFormRef.value.validate((valid) => {
    if (valid) {
      if (categoryForm.value.id) {
        // 更新操作
        // 实际项目中需要更新树结构
        ElMessage.warning('编辑分类功能尚未完全实现');
      } else {
        // 新增操作
        const newId = Math.max(0, ...flattenTree(categoryTree.value).map(item => item.id)) + 1;
        const newCategory = {
          id: newId,
          label: categoryForm.value.name,
          children: [],
        };

        // 找到父节点
        const parentNode = findNodeById(categoryTree.value, categoryForm.value.parentId);
        if (parentNode) {
          if (!parentNode.children) {
            parentNode.children = [];
          }
          parentNode.children.push(newCategory);
        } else {
          // 默认添加到根节点
          categoryTree.value[0].children.push(newCategory);
        }

        // 更新扁平化列表
        updateFlatCategoryList();
      }

      categoryDialogVisible.value = false;
      ElMessage.success('保存成功');
    } else {
      ElMessage.error('表单验证失败，请检查');
      return false;
    }
  });
};

// 辅助方法：通过ID查找树节点
const findNodeById = (tree, id) => {
  for (const item of tree) {
    if (item.id === id) {
      return item;
    }
    if (item.children && item.children.length > 0) {
      const found = findNodeById(item.children, id);
      if (found) return found;
    }
  }
  return null;
};

// 更新扁平化分类列表
const updateFlatCategoryList = () => {
  flatCategoryList.value = flattenTree(categoryTree.value[0].children, 1).map(item => ({
    id: item.id,
    label: '─'.repeat(item.level) + ' ' + item.label,
  }));
};

// 导入导出
const handleImport = () => {
  importDialogVisible.value = true;
};

const handleExport = () => {
  ElMessage.info('导出功能尚未完全实现');
};

const beforeUpload = (file) => {
  const isExcel = file.name.endsWith('.xlsx') || file.name.endsWith('.xls');
  if (!isExcel) {
    ElMessage.error('只能上传 xlsx/xls 文件');
    return false;
  }
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB');
    return false;
  }
  return true;
};

const handleUploadSuccess = (response) => {
  console.log('上传成功：', response);
  ElMessage.success('文件上传成功');
};

const handleUploadError = (err) => {
  console.error('上传失败：', err);
  ElMessage.error('文件上传失败');
};

const submitImport = () => {
  // 模拟导入操作
  importDialogVisible.value = false;
  ElMessage.success('导入成功');
};

// 刷新
const handleRefresh = () => {
  // 模拟刷新操作
  ElMessage.success('数据已刷新');
};

// 生命周期钩子
onMounted(() => {
  // 初始化扁平化分类列表
  updateFlatCategoryList();
  
  // 默认选中第一个组装件
  if (assemblyList.value.length > 0) {
    handleRowClick(assemblyList.value[0]);
  }
});
</script>

<style scoped>
.bom-template-container {
  padding: 16px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.toolbar {
  margin-bottom: 16px;
}

.search-form {
  margin-bottom: 16px;
  background-color: #f5f7fa;
  padding: 16px;
  border-radius: 4px;
}

.content-area {
  flex: 1;
  display: flex;
  gap: 16px;
}

.left-panel {
  width: 240px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.category-header {
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  gap: 8px;
}

.category-tree {
  flex: 1;
  overflow: auto;
  padding: 8px;
}

.right-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.assembly-card, .subassembly-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.card-actions {
  display: flex;
  gap: 8px;
}

.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.empty-table {
  padding: 20px;
}
</style>